<?php

declare(strict_types=1);

namespace app\model\admin;

use app\eslib\CommonUtils;
use app\eslib\StringUtils;
use think\Model;


/**
 * 短信验证码表 数据模型类
 */
class EsxdmSysSmsCaptchaModel extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'esxdm_sys_sms_captcha';

    // 自动时间戳
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    /**
     * 创建一条新记录
     */
    public static function createRecord($userId, $mobile, $event, $ip, $len = 4)
    {
        if ($len < 4) {
            $len = 4;
        }
        if ($len > 8) {
            $len = 8;
        }
        $data = [
            'user_id' => $userId,
            'mobile' => $mobile,
            'event' => $event,
            'code' => StringUtils::newNum($len),
            'ip' => $ip,
        ];
        $model = self::create($data);
        return $model;
    }
    /**
     * 检测验证码是否正确
     */
    public static function checkCodeByMobile($mobile, $event, $code, $expireSecond = 3000)
    {
        return self::checkCode('mobile', $mobile, $event, $code, $expireSecond);
    }
    /**
     * 检测验证码是否正确
     */
    public static function checkCodeByUserId($userId, $event, $code, $expireSecond = 3000)
    {
        return self::checkCode('user_id', $userId, $event, $code, $expireSecond);
    }
    /**
     * 检测验证码是否正确
     */
    public static function checkCode($fieldName, $fieldValue, $event, $code, $expireSecond = 3000)
    {
        if (!$fieldName || !$fieldValue || $event == '' || $code == '') {
            return CommonUtils::stdmessage(0, '参数不完整');
        }
        $smsInfo = self::where($fieldName, $fieldValue)->where('event', $event)->order('id desc')->field('code, created_at')->find();
        if (!$smsInfo) {
            return CommonUtils::stdmessage(0, '查无验证码', compact('fieldValue', 'event', 'code'));
        }
        if ($smsInfo->code != $code) {
            return CommonUtils::stdmessage(0, '验证码错误');
        }
        if (($smsInfo->getData('created_at') + $expireSecond) < time()) {
            return CommonUtils::stdmessage(0, '验证码已过期');
        }
        return CommonUtils::stdmessage(1, '校验通过');
    }
    /**
     * 检测安全限制
     */
    public static function checkSafeLimit($mobile, $event, $ip)
    {
        // 时间间隔限制
        $createTime = self::where('mobile', $mobile)->where('event', $event)->order('id desc')->value('created_at');
        if ($createTime && time() - $createTime < 60) {
            return CommonUtils::stdmessage(0, '发送过于频繁', '时间间隔 60 秒');
        }
        // IP次数限制
        $ipTotalCount = self::where('ip', $ip)->where('created_at', '>', strtotime('-1 hours'))->count();
        if ($ipTotalCount >= 5) {
            return CommonUtils::stdmessage(0, '发送过于频繁', '每天最多 5 条');
        }
        return CommonUtils::stdmessage(1, '');
    }
}
